package io.github.mosiki.modules.sys.service.impl;

import io.github.mosiki.modules.sys.domain.SysRoleMenu;
import io.github.mosiki.modules.sys.repository.SysRoleMenuRepository;
import io.github.mosiki.modules.sys.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl implements SysRoleMenuService{
    @Autowired
    private SysRoleMenuRepository sysRoleMenuRepository;

    @Override
    public List<Long> listMenuId(Long roleId) {
        return sysRoleMenuRepository.listMenuId(roleId);
    }

    @Override
    public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
        //先删除角色与菜单关系
        deleteBatchByRoleId(new Long[]{roleId});

        if(menuIdList.size() == 0){
            return ;
        }

        //保存角色与菜单关系
        List<SysRoleMenu> list = new ArrayList<>(menuIdList.size());
        for(Long menuId : menuIdList){
            SysRoleMenu sysRoleMenuEntity = new SysRoleMenu();
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuEntity.setRoleId(roleId);

            list.add(sysRoleMenuEntity);
        }
        sysRoleMenuRepository.saveAll(list);
    }

    @Override
    public void deleteBatchByRoleId(Long[] roleIds) {
        sysRoleMenuRepository.deleteBatchByRoleId(roleIds);
    }

    @Override
    public int deleteBatchByMenuId(long menuId) {
        return sysRoleMenuRepository.deleteBatchByMenuId(menuId);
    }
}
